<template>
  <el-form :model="userData" :rules="rules" ref="registrationForm">
    <!--    用户名和密码字段-->
    <el-form-item label="工号" prop="username">
      <el-input v-model="userData.username"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input type="password" v-model="userData.password"></el-input>
    </el-form-item>
    <el-form-item label="确认密码" prop="confirm_password">
      <el-input type="password" v-model="userData.confirm_password"></el-input>
    </el-form-item>
    <!-- 发送与接收邮箱-->
<!--    <el-form-item label="邮箱" prop="email">
      <el-input v-model="userData.email"></el-input>
    </el-form-item>-->
    <!-- 邮箱验证码-->
<!--    <el-form-item label="邮箱验证码" prop="email_code">
      <el-input v-model="userData.email_code">
        <template #append>
          <el-button
              type="primary"
              size="small"
              :loading="VerificationCodeing"
              :disabled="VerificationCodeing"
              @click="sendVerificationCode">
            {{ VerificationCodeing && countdown > 0 ? `${countdown}秒后重新发送` : '验证' }}
          </el-button>
        </template>
      </el-input>

    </el-form-item>-->
    <!-- 其他字段可以继续添加 -->
    <el-form-item
        v-for="(value, key) in user_userInfo"
        :key="key"
        :label="value.verbose_name"
        :prop="key">
      <component
          :is="inputComponentForType(value, key).component"
          v-model="userData[key]"
          v-bind="inputComponentForType(value, key).props"
      >
        <!-- 当组件为el-select时，渲染options -->
        <template v-if="inputComponentForType(value, key).component === ElSelect">
          <el-option
              v-for="option in value.choices"
              :key="option"
              :label="option"
              :value="option"
          ></el-option>
        </template>
      </component>
    </el-form-item>


    <el-form-item>
      <el-button type="primary"
                 :loading="registerLoading"
                 :disabled="registerLoading"
                 @click="submitForm">{{ registerLoading ? '正在注册' : '注册' }}
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import {ref, reactive, onMounted, watchEffect, onBeforeUnmount} from 'vue'
import setting from "@/setting.js";
import {ElDatePicker, ElInput, ElMessage, ElSelect, ElSwitch, ElText} from "element-plus";
import {jsonApi} from "@/global.js";

const registrationForm = ref(null);
const userData =  reactive({confirm_password: '' })
const user_userInfo = ref({})
// const confirm_password = ref('')
const rules = reactive({
  /*{
    "User": {
        "model_name": "用户",
        "id": {
            "type": "BigAutoField",
            "verbose_name": "ID",
            "choices": null
        },
        "is_superuser": {
            "type": "BooleanField",
            "verbose_name": "超级用户状态",
            "choices": null
        },
        "username": {
            "type": "CharField",
            "verbose_name": "用户名",
            "choices": null
        },
        "email": {
            "type": "EmailField",
            "verbose_name": "电子邮件地址",
            "choices": null
        },
        "name": {
            "type": "CharField",
            "verbose_name": "姓名",
            "choices": null
        },
        "title": {
            "type": "CharField",
            "verbose_name": "职称",
            "choices": [
                "讲师",
                "副教授",
                "教授",
                "助教",
                "无"
            ]
        },
        "avatar": {
            "type": "CharField",
            "verbose_name": "头像",
            "choices": null
        },
        "phone_num": {
            "type": "CharField",
            "verbose_name": "手机号",
            "choices": null
        },
        "contact_address": {
            "type": "CharField",
            "verbose_name": "联系地址",
            "choices": null
        },
        "is_cp": {
            "type": "BooleanField",
            "verbose_name": "是否是共产党员",
            "choices": null
        },
        "degree": {
            "type": "CharField",
            "verbose_name": "学位",
            "choices": [
                "学士",
                "硕士",
                "博士"
            ]
        },
        "is_good_teacher": {
            "type": "CharField",
            "verbose_name": "是否是名师",
            "choices": [
                "校级教学名师",
                "集团级教学名师",
                "市厅级教学名师",
                "省级教学名师",
                "国家级教学名师",
                "不是名师"
            ]
        },
        "department": {
            "type": "CharField",
            "verbose_name": "所属教研室",
            "choices": [
                "数智教研室",
                "计算机教研室",
                "通号教研室",
                "非教研室人员"
            ]
        },
        "other_title": {
            "type": "CharField",
            "verbose_name": "其它头衔",
            "choices": null
        },
        "base_score": {
            "type": "FloatField",
            "verbose_name": "基础评分",
            "choices": null
        }
    }
}*/
  username: [
    {required: true, message: '请输入用户名', trigger:  ['blur', 'change']}
  ],
  password: [
    {required: true, message: '请输入密码', trigger:  ['blur', 'change']}
  ],
  confirm_password : [
    {required: true, message: '请输入确认密码', trigger:  ['blur', 'change']},
    {
      validator: (rule, value, callback) => {
        if (value !== userData.password) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      },
      trigger:  ['blur', 'change']
    }
  ],
  email: [
    {required: true, message: '请输入邮箱', trigger:  ['blur', 'change']}
  ],
  email_code: [
    {required: true, message: '请输入邮箱验证码', trigger:  ['blur', 'change']}
  ],
  name: [
    {required: true, message: '请输入姓名', trigger:  ['blur', 'change']}
  ],

  phone_num: [
    {required: true, message: '请输入手机号', trigger:  ['blur', 'change']}
  ],
  contact_address: [
    {required: true, message: '请输入联系地址', trigger:  ['blur', 'change']}
  ],
  degree: [
    {required: true, message: '请选择学位', trigger: 'change'}
  ],
  is_good_teacher: [
    {required: true, message: '请选择是否是名师', trigger: 'change'}
  ],
  department: [
    {required: true, message: '请选择所属教研室', trigger: 'change'}
  ],
  title: [
    {required: true, message: '请选择职称', trigger: 'change'}
  ],

})

const inputComponentForType = (value, key) => {
  const componentMap = {
    'CharField': ElInput,
    'IntegerField': ElInput,
    'DateTimeField': ElDatePicker,
    'BooleanField': ElSwitch,
  };

  if (value.type === 'JSONField') {
    return {component: ElText, props: {readonly: true}};
  }
  if (value.choices !== null) {
    return {
      component: ElSelect,
      props: {
        options: value.choices.map(choice => ({
          label: choice,
          value: choice,
        }))
      }
    };
  }

  return {
    component: componentMap[value.type] ? componentMap[value.type] : ElInput,
    props: {}
  };


};

//初始化函数
const getReportInfo = async () => {
  //获取时需要排除的字段
  if (!localStorage.getItem('registeinfo')) {
    const response = await jsonApi('/user/getfields/',"",false);
    const data = await response.json();
    if (response.ok) {
      localStorage.setItem('registeinfo', JSON.stringify(data));
      await getReportInfo();
    } else {
      showError('获取报告信息失败', data.error, 2000);
    }
  }
  //将字符串转为对象

  user_userInfo.value = JSON.parse(localStorage.getItem('registeinfo'))['User'];
  const get_excludeFields = ['id', 'model_name', 'attachment', 'username', 'password', "is_superuser", "avatar", 'email', 'base_score'];
  // 使用 forEach 循环来遍历对象的所有键
  get_excludeFields.forEach(field => {
    // 如果报告信息中存在要排除的字段，则删除它
    if (user_userInfo.value.hasOwnProperty(field)) {
      delete user_userInfo.value[field];
    }
  });
};
let VerificationCodeing = ref(false);
let countdown = ref(0);
let timer = null; // 不再使用ref，因为定时器句柄不需要响应式
const sendVerificationCode = async () => {
  try {
    /*/user/getcode/
    * */
    VerificationCodeing.value = true;
    countdown.value = 60;
    timer = setInterval(() => {
      if (countdown.value <= 0) {
        clearInterval(timer);
        VerificationCodeing.value = false;
        countdown.value = 0;
        timer = null;
      } else {
        countdown.value -= 1;
      }
    }, 1000); // 每秒减少1
    const response = await jsonApi('/user/getcode/',JSON.stringify({
        email: userData.email
      }),false);
    const data = await response.json();
    if (response.ok) {
      ElMessage({message: '获取验证码成功', type: 'success', duration: 2000});
    } else {
      ElMessage({
        type: 'error',
        message: '获取验证码失败:' + data.error,
        duration: 2000
      });
      countdown.value = 0;
    }

  } catch (e) {
    ElMessage({
      type: 'error',
      message: '发送验证码失败:' + e,
      duration: 2000
    });
    countdown.value = 0;
  }
}
const registerLoading = ref(false);
const submitForm = async () => {
  registerLoading.value = true;
  registrationForm.value.validate(async (valid) => {
    if (valid) {
      // 表单验证通过后的操作
      try {
        const response = await jsonApi('/user/register/',JSON.stringify(userData),false);
        const data = await response.json();
        if (response.ok) {
          //跳转登录
          ElMessage({message: '注册成功-两秒后跳转', type: 'success', duration: 2000});
          //等待两秒
          await new Promise(resolve => setTimeout(resolve, 2000));
          window.location.href = '/#/login';
          registerLoading.value = false;
        } else {
          ElMessage({
            type: 'error',
            message: '注册失败:' + data.error,
            duration: 2000
          });
          registerLoading.value = false;
        }
      } catch (e) {
        ElMessage({
          type: 'error',
          message: '注册失败:' + e,
          duration: 2000
        });
        registerLoading.value = false;

      }
    } else {
      ElMessage({
        type: 'error',
        message: '注册失败:请确保填报信息完整',
        duration: 2000
      });
      registerLoading.value = false;
    }
  });

  /*
  * /user/register/*/


};
watchEffect(async () => {

  await getReportInfo();

});
// 清理定时器的钩子
onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer);
  }
});

</script>